package com.elite.groovy.dev;

import com.elite.groovy.kh.KHUtil;
import net.sf.json.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.websocket.*;
import java.net.URI;

@ClientEndpoint
public class WebSocketClient {
    private static final Log log = LogFactory.getLog(WebSocketClient.class);

    @OnOpen
    public void onOpen(Session session) {
        log.debug("Connection established");
        try {
            // 发送一条消息到服务器
            session.getBasicRemote().sendText("Hello, WebSocket Server!");
            log.debug("建立连接");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @OnMessage
    public void onMessage(String message) {
        log.debug("Received message: " + message);
    }

    @OnClose
    public void onClose(Session session, CloseReason reason) {
        log.debug("Connection closed: " + reason.getReasonPhrase());
    }


    public static void pushMessage(String url, String message) {
        Session session = null;
        try {
            WebSocketContainer container = ContainerProvider.getWebSocketContainer();
            session = container.connectToServer(WebSocketClient.class, new URI(url));
            session.getBasicRemote().sendText(message);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (session != null) {
                try {
                    session.close();
                } catch (Exception e) {
                    log.error("pushMessage发送消息异常", e);
                }
            }
        }
    }

    public static void main(String[] args) {
        String socketMsg = "{\"source\":\"SELIET\",\"target\":\"000001\",\"targetType\":0,\"clientType\":\"pc\",\"message\":\"" + KHUtil.getRandomString(4) + "\",\"refid\":\"" + KHUtil.getRandomString(36) + "\",\"module\":\"\"}";

        JSONObject socketJson = JSONObject.fromObject(socketMsg);
        WebSocketClient.pushMessage("ws://127.0.0.1:8080/ngs/ws", socketJson.toString());
    }
}